﻿// // ******************************************************************
// //       /\ /|       @file       SubtitleHelp.cs
// //       \ V/        @brief      await29
// //       | "")       @author     Await, 285283010@qq.com
// //       /  |
// //      /  \\        @Modified   2024-12-23 14:12
// //    *(__\_\        @Copyright  Copyright (c) , 2024-12-23 14:12 Await
// // ******************************************************************

using System.Text;
using System.Text.RegularExpressions;
using AutomaticSubtitles.Contracts.Entity;

namespace AutomaticSubtitles.Service.Infrastructure.Helper;

public static class SubtitleHelp
{
    // 定义样式标签的正则表达式
    public static readonly Regex AssStyleRegex = new(@"({\\.*?})", RegexOptions.Compiled);
    public static readonly Regex SrtStyleRegex = new(@"<[^>]+>", RegexOptions.Compiled);

    //定义头部信息的正则表达式
    public static readonly Regex ScriptInfoRegex = new(@"^\[Script Info\]", RegexOptions.Compiled);
    public static readonly Regex StylesRegex = new(@"^\[V4\+? Styles\]", RegexOptions.Compiled);
    public static readonly Regex EventsRegex = new(@"^\[Events\]", RegexOptions.Compiled);
    public static readonly Regex HeaderLineRegex = new(@"^(Format|Style|Dialogue):", RegexOptions.Compiled);


    public static (string cleanText, string style) ExtractStyleAndContent(string text)
    {
        var style = new StringBuilder();

        // 提取 ASS/SSA 样式
        var assMatches = AssStyleRegex.Matches(text);
        foreach (Match match in assMatches) style.Append(match.Value);
        var cleanText = AssStyleRegex.Replace(text, "");

        // 提取 SRT 样式
        var srtMatches = SrtStyleRegex.Matches(cleanText);
        foreach (Match match in srtMatches) style.Append(match.Value);
        cleanText = SrtStyleRegex.Replace(cleanText, "");

        return (cleanText.Trim(), style.ToString());
    }

    public static string RestoreStyle(string translatedText, string style)
    {
        // 如果是 ASS/SSA 样式，在每行开头添加样式
        if (style.StartsWith("{\\")) return style + translatedText;
        // 如果是 SRT 样式，在整个文本外部添加样式
        if (!style.StartsWith("<")) return translatedText;
        // 处理嵌套的样式标签
        var openTags = new List<string>();
        var closeTags = new List<string>();

        var matches = SrtStyleRegex.Matches(style);
        foreach (Match match in matches)
        {
            var tag = match.Value;
            if (tag.StartsWith("</")) continue;
            openTags.Add(tag);
            closeTags.Insert(0, tag.Insert(1, "/")); // 创建对应的关闭标签
        }

        return string.Join("", openTags) + translatedText + string.Join("", closeTags);
    }


    public static List<SubtitleInfo>? ParseSubtitleFile(string filePath)
    {
        var subtitles = new List<SubtitleInfo>();

        // 检查文件是否存在
        if (!File.Exists(filePath))
        {
            throw new FileNotFoundException("未找到字幕文件", filePath);
        }

        var lines = File.ReadAllLines(filePath);
        var currentEntry = new SubtitleInfo();
        var isReadingContent = false;
        var contentBuilder = new StringBuilder();

        foreach (var line in lines)
        {
            var trimmedLine = line.Trim();

            // 跳过空行
            if (string.IsNullOrWhiteSpace(trimmedLine))
            {
                if (isReadingContent)
                {
                    // 完成当前字幕条目的读取
                    // currentEntry.Content = CleanSubtitleText(contentBuilder.ToString().Trim());
                    // ExtractStyleAndContent
                    var (cleanText, style) = ExtractStyleAndContent(contentBuilder.ToString().Trim());
                    currentEntry.Content = cleanText;
                    subtitles.Add(currentEntry);
                    currentEntry = new SubtitleInfo();
                    contentBuilder.Clear();
                    isReadingContent = false;
                }
                continue;
            }

            // 解析时间行
            if (trimmedLine.Contains("-->"))
            {
                var times = trimmedLine.Split(new[] { "-->" }, StringSplitOptions.RemoveEmptyEntries);
                currentEntry.StartTime = ParseTimeSpan(times[0].Trim());
                currentEntry.EndTime = ParseTimeSpan(times[1].Trim());
                isReadingContent = true;
                continue;
            }

            // 如果是内容行，添加到内容构建器
            if (isReadingContent)
            {
                contentBuilder.AppendLine(trimmedLine);
            }
        }

        return subtitles;
    }

    private static TimeSpan ParseTimeSpan(string timeText)
    {
        // 处理时间格式 00:00:00,000
        var parts = timeText.Replace(',', ':').Split(':');
        return new TimeSpan(0,
            int.Parse(parts[0]), // 小时
            int.Parse(parts[1]), // 分钟
            int.Parse(parts[2]), // 秒
            int.Parse(parts[3])); // 毫秒
    }
}